package com.shaoshaohuo.app.ui.ec;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.EvaluationSimpleAdapter;
import com.shaoshaohuo.app.adapter.SpecificationAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.UMengEventID;
import com.shaoshaohuo.app.entity.Address;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.EvaluationListEntity;
import com.shaoshaohuo.app.entity.Specification;
import com.shaoshaohuo.app.entity.SupplyDetailEntity;
import com.shaoshaohuo.app.entity.SupplyOrder;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.OtherEvaluationActivity;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.SpecificationDataUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.utils.sharesdk.ShareContent;
import com.shaoshaohuo.app.utils.sharesdk.ShareFactory;
import com.shaoshaohuo.app.view.EcCreateOrderPopupWindow;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.wxstyle.ImagePagerActivity;
import com.shaoshaohuo.app.view.wxstyle.NoScrollGridAdapter;
import com.shaoshaohuo.app.view.wxstyle.NoScrollGridView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform.ShareParams;

/**
 * @author linmu
 * @ClassName ProductDetailActivity
 * @Decription 供应详情 @2015-8-30 下午5:40:43
 */
public class SupplyDetailActivity extends BaseActivity implements OnClickListener {

    private TopbarView mTopbarView;

    private boolean isRecord;
    private String id;

    private TextView tv_name;
    private TextView tv_pinzhong;
    private TextView tv_price;
    private TextView tv_unit;
    private ImageView iv_shichang;
    private ImageView iv_shuai;
    private TextView tv_address;
    private TextView tv_num;
    private TextView tv_xianzhi;
    private TextView tv_date;
    private GridView gv_specification;
    private FrameLayout fl_specification;
    private TextView tv_miaoshu;

    private ImageView iv_wechat;
    private ImageView iv_call; // 1.8.2
    private TextView tv_username;

    private TextView tv_comment_num;
    private ListView mlv_comment;

    private TextView textview_star;
    private RatingBar ratingbar;
    private LinearLayout ll_commnet;

    private Button mNextButton;
    private Button mAddToCartButton;

    private SupplyOrder data;
    private NoScrollGridView gridview;
    private ArrayList<String> imageUrls;
    private ArrayList<String> smallImageUrls;

    private EcCreateOrderPopupWindow createOrderPopupWindow;


    public static final int REQUEST_CODE_ADDRESS = 1;
    //Extra 标志是否来自品牌直营
    public static final String EXTRA_IS_FROM_BRAND_SCOPE = "EXTRA_IS_FROM_BRAND_SCOPE";
    //是否来自品牌直营
    private boolean isFromBrandScope = false;
    private LinearLayout ll_supply_num;
    private LinearLayout ll_sell_date;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);

        initData();
        initView();
        setUpView();
        requestData();
//        requestComment();
    }

    private void initData() {
        id = getIntent().getStringExtra(ExtraName.id);
        isRecord = getIntent().getBooleanExtra("myinfo", false);
        String strFromBrand = getIntent().getStringExtra(EXTRA_IS_FROM_BRAND_SCOPE);
        if (strFromBrand != null) {
            isFromBrandScope = true;
        }
    }


    private void initView() {

        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);
        mNextButton = (Button) this.findViewById(R.id.button_next);
        mAddToCartButton = (Button) this.findViewById(R.id.button_cart);
        gridview = (NoScrollGridView) this.findViewById(R.id.gridview);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_pinzhong = (TextView) findViewById(R.id.tv_pinzhong);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_unit = (TextView) findViewById(R.id.tv_unit);
        iv_shichang = (ImageView) findViewById(R.id.iv_shichang);
        iv_shuai = (ImageView) findViewById(R.id.iv_shuai);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_xianzhi = (TextView) findViewById(R.id.tv_xianzhi);
        tv_date = (TextView) findViewById(R.id.tv_date);
        gv_specification = (GridView) findViewById(R.id.gv_specification);
        fl_specification = (FrameLayout) findViewById(R.id.fl_specification);
        tv_miaoshu = (TextView) findViewById(R.id.tv_miaoshu);

        iv_wechat = (ImageView) findViewById(R.id.iv_wechat);// 1.8.2
        iv_call = (ImageView) findViewById(R.id.iv_call);
        tv_username = (TextView) findViewById(R.id.tv_username);

        tv_comment_num = (TextView) findViewById(R.id.tv_comment_num);
        mlv_comment = (ListView) findViewById(R.id.mlv_comment);

        textview_star = (TextView) findViewById(R.id.textview_star);
        ratingbar = (RatingBar) findViewById(R.id.ratingbar);
        ll_commnet = (LinearLayout) findViewById(R.id.ll_commnet);
        ll_supply_num = (LinearLayout) findViewById(R.id.layout_supply_num);
        ll_sell_date = (LinearLayout) findViewById(R.id.layout_sell_date);


        createOrderPopupWindow = new EcCreateOrderPopupWindow(this, false);


        if (isRecord == true) {
            mNextButton.setVisibility(View.GONE);
            mAddToCartButton.setVisibility(View.GONE);
        }
    }


    private void setUpView() {
        if (isFromBrandScope) {
            tv_address.setVisibility(View.GONE);
            ll_supply_num.setVisibility(View.GONE);
            ll_sell_date.setVisibility(View.GONE);
        }
        mTopbarView.setCenterText("供应详情");
        mTopbarView.setLeftView(true, true);
        mTopbarView.setRightText("分享赚积分");
        mTopbarView.setRightClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                ShareParams params = new ShareParams();
                params.setTitle(ShareContent.getSupplyTitle(getProductName(data), getPrice()));
                params.setTitleUrl(HttpConfig.WebPage.SHARE_SUPPLY + "?number=" + data.getNumber());
                params.setText(ShareContent.getSupplyText(getProductName(data), getPrice(), data.getRealname(), data.getAddress()));
                if (data.getImages() != null && data.getImages().length > 0) {
                    params.setImageUrl(data.getImages()[0]);
                } else {
                    params.setImageUrl(HttpConfig.WebPage.SHARE_IMAGE_PATH);
                }
                params.setUrl(HttpConfig.WebPage.SHARE_SUPPLY + "?number=" + data.getNumber());
                ShareFactory.showShare(SupplyDetailActivity.this, params,null);
            }
        });

        // if(isRecord){
        // mNextButton.setText("我不卖了");
        // }

        mNextButton.setOnClickListener(this);
        mAddToCartButton.setOnClickListener(this);

        iv_call.setOnClickListener(this);
        iv_wechat.setOnClickListener(this);
        ll_commnet.setOnClickListener(this);

        // 点击回帖九宫格，查看大图
        gridview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                imageBrower(position, imageUrls);
            }
        });
    }

    /**
     * 获取产品的全名 例1：菜花/红菜花 例2：菜花
     *
     * @param data2
     * @return
     */
    private String getProductName(SupplyOrder data2) {
        if (data2.getCatname() == null) {
            return data2.getPidname() == null ? "" : data2.getPidname();
        }
        return data2.getPidname() + "/" + data2.getCatname();
    }

    private String getPrice() {
        return "￥" + data.getMoney() + "元/" + data.getUnit();
    }

    private void requestData() {
        startLoadingDialog();
        RequestService.getInstance().getSupplyDetail(this, id, SupplyDetailEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    SupplyDetailEntity entity = (SupplyDetailEntity) resultData;
                    updateUi(entity);
                    requestComment();
                } else {
                    showToast(resultData.getMsg());
                }
            }


            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });

    }

    protected void updateUi(SupplyDetailEntity entity) {
        data = entity.getData();
        setMainImages(data.getImages());
        mTopbarView.setCenterText(data.getTitle());
        tv_name.setText(data.getPidname());
        tv_pinzhong.setText(data.getCatname());

        String moneyType = data.getMoneyType();
        if ("origin".equals(moneyType)) {
            iv_shichang.setVisibility(View.GONE);
        } else if ("market".equals(moneyType)) {

        }

        if (data.specifications != null && data.specifications.size() > 0) {
            final Map<Specification, List<Specification>> specificationMap = SpecificationDataUtil.list2map(data.specifications);
            gv_specification.setAdapter(new SpecificationAdapter(this, gv_specification, specificationMap));
        } else {
            fl_specification.setVisibility(View.GONE);
        }


        tv_price.setText(data.getMoney());
        tv_unit.setText("元/" + data.getUnit());
        iv_shuai.setVisibility("1".equals(data.getShuai()) ? View.VISIBLE : View.GONE);
        tv_address.setText(AreaUtil.getAreaFullname(data.getCityid()) + data.getAddress());
        tv_num.setText(data.getNumber());
        tv_xianzhi.setText(data.getMinsell() + data.getUnit());
        tv_username.setText(data.getRealname());

        if (TextUtils.isEmpty(data.getStart())) {
            if (TextUtils.isEmpty(data.getEnd())) {
                tv_date.setText("上市时间：至长期");
            } else {
                tv_date.setText("上市时间：至" + data.getEnd());
            }
        } else {
            if (TextUtils.isEmpty(data.getEnd())) {
                tv_date.setText("上市时间：" + data.getStart() + "至长期");
            } else {
                tv_date.setText("上市时间：" + data.getStart() + "-" + data.getEnd());
            }
        }


        tv_miaoshu.setText(data.getContent());
    }

    /*
    获得此商品评论数
     */
    private void requestComment() {
        RequestService.getInstance().getEvaluationList(this, null, id, "3", "5" + "", null, "new", EvaluationListEntity.class,
                new RequestListener() {

                    @Override
                    public void onSuccess(int requestCode, BaseEntity resultData) {
                        if (resultData.isOk()) {
                            EvaluationListEntity entity = (EvaluationListEntity) resultData;
                            if (entity.getData() != null && entity.getData().getList() != null && entity.getData().getList().size() > 0) {
                                tv_comment_num.setText("宝贝评价(" + entity.getData().getStartnum() + ")");
                                ratingbar.setRating(Float.parseFloat(entity.getData().getStartnum()));
                                textview_star.setText("(" + entity.getData().getStartnum() + ")");

                                mlv_comment.setAdapter(new EvaluationSimpleAdapter(SupplyDetailActivity.this, entity.getData().getList(), false));
                            } else {
                                tv_comment_num.setText("此商品暂无评论");
                                ratingbar.setVisibility(View.GONE);
                                textview_star.setVisibility(View.GONE);
                                ll_commnet.setEnabled(false);
                            }
                        } else {
                            showToast(resultData.getMsg());
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, Exception error, String msg) {
                        showToast(R.string.please_check_network);
                    }
                });
    }


    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }

    private void cancelOrder() {
        startLoadingDialog();
        RequestService.getInstance().cancelSupplyOrder(this, id, BaseEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    showToast("订单取消成功");
                    finish();
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }

    protected void setMainImages(String[] images) {

        imageUrls = new ArrayList<String>();
        smallImageUrls = new ArrayList<String>();
        if (images != null) {
            for (String im : images) {
//				while (im.startsWith("null")) {
//					im = im.substring(4);
//				}


                imageUrls.add(im);
                int lastPos = im.lastIndexOf(".");
                if (lastPos > 0) {
                    smallImageUrls.add(im.substring(0, lastPos) + "_small" + im.substring(lastPos, im.length()));
                } else {
                    smallImageUrls.add(im);
                }
            }
        }
        if (imageUrls.isEmpty()) { // 没有图片资源就隐藏GridView
            gridview.setVisibility(View.GONE);
        } else {
            gridview.setAdapter(new NoScrollGridAdapter(this, smallImageUrls));
            gridview.setVisibility(View.VISIBLE);
        }
    }

    public int currentItem;

    private PopupWindow hintPopWinwow;

    public void shareMsg() {
        if (hintPopWinwow != null && hintPopWinwow.isShowing()) {
            hintPopWinwow.dismiss();
            return;
        }
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View contentView = inflater.inflate(R.layout.view_share_dialog, null, false);
        hintPopWinwow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT, true);
        hintPopWinwow.setOutsideTouchable(true);
        hintPopWinwow.setBackgroundDrawable(new BitmapDrawable());
        hintPopWinwow.setAnimationStyle(R.style.Anim_Dialog_Bottom);
        View sinaLayout = contentView.findViewById(R.id.layout_share_sina);
        View qqLayout = contentView.findViewById(R.id.layout_share_qq);
        View qqzoneLayout = contentView.findViewById(R.id.layout_share_qqzone);
        View weixinLayout = contentView.findViewById(R.id.layout_share_weixin);
        View pengyouquanLayout = contentView.findViewById(R.id.layout_share_pengyouquan);
        View contactLayout = contentView.findViewById(R.id.layout_share_sms);
        View closeLayout = contentView.findViewById(R.id.textview_close);

        sinaLayout.setOnClickListener(this);
        qqLayout.setOnClickListener(this);
        qqzoneLayout.setOnClickListener(this);
        weixinLayout.setOnClickListener(this);
        pengyouquanLayout.setOnClickListener(this);
        contactLayout.setOnClickListener(this);
        closeLayout.setOnClickListener(this);

        hintPopWinwow.showAtLocation(mTopbarView, Gravity.BOTTOM, 0, 0);
    }

    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_next:
                MobclickAgent.onEvent(this, UMengEventID.CLICK_EC_SUPPLY_ORDER_DIRECT);
                if (AccountManager.checkUserAuth(this)) {
                    if (data == null) {
                        showToast("暂时无法下单");
                        return;
                    }
                    createOrderPopupWindow.setSupplyid(id);
                    createOrderPopupWindow.setUnit(data.getUnit());
                    createOrderPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                    createOrderPopupWindow.showAtLocation(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0),
                            Gravity.BOTTOM, 0, 0);
                }
                return;
            case R.id.button_cart:
                MobclickAgent.onEvent(this, UMengEventID.CLICK_EC_SUPPLY_ORDER_CART);
                if (AccountManager.checkUserAuth(this)) {
                    addGoodToCart();
                }
                return;
        /*case R.id.layout_share_sina:
            AndroidUtils.sendweibo(this, ShareContent.SHARE_TITLE, ShareContent.SUPPLY_CONTENT,
					HttpConfig.WebPage.SHARE);
			break;
		case R.id.layout_share_qq:
			AndroidUtils.sendqq(this, HttpConfig.WebPage.SHARE, ShareContent.SHARE_TITLE, ShareContent.SUPPLY_CONTENT);
			break;
		case R.id.layout_share_qqzone:
			AndroidUtils.sendkongjian(this, HttpConfig.WebPage.SHARE, ShareContent.SHARE_TITLE,
					ShareContent.SUPPLY_CONTENT);
			break;
		case R.id.layout_share_weixin:
			AndroidUtils.sendweixin(this, ShareContent.SHARE_TITLE, ShareContent.SUPPLY_CONTENT,
					HttpConfig.WebPage.SHARE);
			break;
		case R.id.layout_share_pengyouquan:
			AndroidUtils.sendpengyouquan(this, ShareContent.SHARE_TITLE, ShareContent.SUPPLY_CONTENT,
					HttpConfig.WebPage.SHARE);
			break;
		case R.id.layout_share_sms:
			Uri smsToUri = Uri.parse("smsto:");
			Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
			sendIntent.putExtra("sms_body", ShareContent.SUPPLY_CONTENT + HttpConfig.WebPage.SHARE);
			sendIntent.setType("vnd.android-dir/mms-sms");
			startActivity(sendIntent);
			break;*/
            case R.id.textview_close:
                break;
            case R.id.iv_wechat:
                IMFactory.openChat(this, data.getUserid());
                break;
            case R.id.iv_call:
                DeviceHelper.callPhone(this, data.getMobile(), data.getKey());
                break;
            case R.id.ll_commnet:
                //TODO 进入评价详情页面
                Intent intent = new Intent(this, OtherEvaluationActivity.class);
                intent.putExtra(ExtraName.orderid, id);
                startActivity(intent);
                break;
        }

//        hintPopWinwow.dismiss();
    }

    /**
     * 添加到购物车
     */
    private void addGoodToCart() {
        startLoadingDialog();
        RequestService.getInstance().addGoodsToEcCart(this, id, BaseEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    showToast(getString(R.string.alert_msg_save_to_cart_success));
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_ADDRESS:
                if (resultCode == RESULT_OK) {
                    createOrderPopupWindow.setAddress((Address) data.getExtras().get(ExtraName.address));
                }
                break;
            default:
                break;
        }
    }

}
